package ch12_network.udp;

import cn.hutool.core.convert.Convert;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * The class/interface
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
public class ClientServer {
    public static void main(String[] args) throws Exception {
        init();
    }


    public static String inInfo() {
        Scanner scanner = new Scanner(System.in);
        return scanner.next();
    }


    public static void init() throws Exception {
        // 1、实例化套接字
        DatagramSocket ds = new DatagramSocket(8888);
        System.out.print("请输入发送IP：");
        String addr = inInfo();
        System.out.print("请输入发送PORT：");
        String port = inInfo();
        while (true) {
            System.out.print("输入发送内容：");
            String content = inInfo();
            if ("0".equals(content)) {
                break;
            }
            // 2、发送
            byte[] buf = content.getBytes();
            DatagramPacket dp = new DatagramPacket(buf, buf.length,
                    new InetSocketAddress(addr, Convert.toInt(port)));
            ds.send(dp);

            // 3、接收，会阻塞
            byte[] bytes = new byte[1024];
            DatagramPacket res = new DatagramPacket(bytes, bytes.length);
            ds.receive(res);
            System.out.println(new String(bytes, 0, res.getLength()));
        }
        ds.close();
    }
}
